#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy
import time

from cln_msgs.msg import LogMsg
from cln_msgs.srv import *

class Log_Parser:
    def __init__(self):
        self.__max_conut_for_log_query = 500  #单次请求最大日志条数，以防数据量过大

        ##发布topic
        self.__save_log_pub = rospy.Publisher("/log_save", LogMsg, queue_size=100)

        ##服务Proxy
        self.__log_query_client = rospy.ServiceProxy('/log_query',LogQuery)
    
    def ConvertStringtoTime(self, time_str):
        '''
        把格式化的字符串类型的时间转换成rospy.Time格式
        :param time_str: '2022-06-13 20:21:04'
        :return: rospy.Time类型
        '''
        return rospy.Time(time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S")))

    def ConvertTimetoString(self, ros_time):
        '''
        把time格式转换成格式化的字符串类型的时间
        :param time: rospy.Time格式
        :return: String类型: '2022-06-13 20:21:04'
        '''
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ros_time.to_sec()))

    def SaveLog(self, log_level, node_name, log_msg, log_code = 0):
        '''
        保存日志信息
        '''
        log = LogMsg()
        log.log_level = log_level
        log.node_name = node_name
        log.log_time = rospy.Time.now()
        log.log_data.append(log_msg)
        log.log_code = log_code
        self.__save_log_pub.publish(log)
    
    def LogDebug(self, node_name, log_msg, log_code = 0):
        '''
        记录调试信息
        '''
        self.SaveLog(LogMsg.DEBUG, node_name, log_msg, log_code)
    
    def LogInfo(self, node_name, log_msg, log_code = 0):
        '''
        记录正常提示
        '''
        self.SaveLog(LogMsg.INFO, node_name, log_msg, log_code)

    def LogWarn(self, node_name, log_msg, log_code = 0):
        '''
        记录警告信息
        '''
        self.SaveLog(LogMsg.WARN, node_name, log_msg, log_code)

    def LogError(self, node_name, log_msg, log_code = 0):
        '''
        记录错误信息
        '''
        self.SaveLog(LogMsg.ERROR, node_name, log_msg, log_code)

    def LogFatal(self, node_name, log_msg, log_code = 0):
        '''
        记录调试信息
        '''
        self.SaveLog(LogMsg.FATAL, node_name, log_msg, log_code)

    def QueryLogs(self, start_time, end_time, log_level):
        '''
        请求日志信息
        '''
        try:
            if not start_time: raise Exception("start time is empty!")   
            if not end_time: raise Exception("end time is empty!")   
            if not log_level: raise Exception("log level is empty!")   

            logs_req = LogQueryRequest()
            logs_req.start_time = self.ConvertStringtoTime(start_time)
            logs_req.end_time = self.ConvertStringtoTime(end_time)
            logs_req.level.append(log_level)
            res = self.__log_query_client(logs_req)
            if not res.success:  raise Exception(res.message)

            logs_data = []
            count = 0
            for log in res.log_data:
                ##过滤 /robot_log 节点的日志
                if log.node_name == "/robot_log":
                    continue

                log_data = { "node_name" : log.node_name,
                             "log_level" : log.log_level,
                             "log_time" : self.ConvertTimetoString(log.log_time),
                             "log_code" : log.log_code
                            }
                log_msg = ""
                for msg in log.log_data:
                    if log_msg :
                        log_msg += "; "
                    log_msg += msg
                log_data["log_data"] = log_msg
                logs_data.append(log_data)

                ##防止数据过大，导致网络卡死
                count += 1
                if count > self.__max_conut_for_log_query:
                    break
                    
            return True, "success",logs_data

        except Exception as error:
            rospy.logerr("[Log_Parser]Failed to query logs: {}".format(error))
            return False, str(error), [] 

    def GetLogLevelInfo(self):
        '''
        请求日志等级信息列表
        '''
        try:
            level_debug = {"level_value":1,"level_name":"debug","level_name_ch":"调试信息"}
            level_info = {"level_value":2,"level_name":"info","level_name_ch":"正常提示"}
            level_warn = {"level_value":3,"level_name":"warn","level_name_ch":"警告消息"}
            level_error = {"level_value":4,"level_name":"error","level_name_ch":"错误消息"}
            level_fatal = {"level_value":5,"level_name":"fatal","level_name_ch":"严重错误"} 
            log_levels = [level_debug,level_info,level_warn,level_error,level_fatal]

            return True, "success", log_levels
        except Exception as error:
            rospy.logerr("[Log_Parser]Failed to get log level info: {}".format(error))
            return False, str(error), [] 
